import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignDetailVo.dart';
import 'package:ecy_app_flutter/routes/consignment/model/ConsignProduct.dart';
import 'package:ecy_app_flutter/routes/my/model/messgae/ChatSession.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../../common/ChatScreen.dart';

class EcyConsignChatPage extends StatefulWidget {
  late ConsignProduct consignProduct;

  EcyConsignChatPage({
    required super.key,
    required this.consignProduct,
  });

  @override
  State<EcyConsignChatPage> createState() =>
      _EcyConsignChatPageState(consignProduct);
}

class _EcyConsignChatPageState extends State<EcyConsignChatPage> {
  late final ConsignProduct _consignProduct;

  _EcyConsignChatPageState(this._consignProduct);

  bool _loading = false;
  int? _sessionId;

  ConsignDetailVo _consignDetailVo = ConsignDetailVo();
  ChatScreen _chatScreen = ChatScreen(
    chatSession: ChatSession(),
  );

  @override
  void initState() {
    super.initState();

    _loadConsignDetail();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _createSession() async {
    var response = await EcyRequestbasemanager().post(
        "/app/api/app/consign/sessions",
        {"productId": _consignProduct.productId});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        _sessionId = response["data"];
        ChatSession chatSession = ChatSession();
        chatSession.sessionId = _sessionId;
        _chatScreen = ChatScreen(
          key: const Key("ChatScreen"),
          chatSession: chatSession,
          showAppBar: false,
        );
      }
    }
  }

  void _loadConsignDetail() async {
    await _createSession();

    var response = await EcyRequestbasemanager().get(
        "/app/api/app/consign/product/detail?productId=${_consignProduct.productId}",
        {});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        if (response["data"] != null) {
          setState(() {
            _consignDetailVo = ConsignDetailVo.fromJson(response["data"]);
          });
        }
      } else {
        EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
            duration: const Duration(seconds: 2));
      }
    }
  }

  Future<void> _orderCreate() async {
    if (_loading) {
      return;
    }

    setState(() {
      _loading = true;
    });

    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/order/create",
          {"productId": _consignProduct.productId});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          Map<String, dynamic> dataMap = response["data"] as Map<String, dynamic>;
          EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage,
              {"orderCode": dataMap['orderCode'], "type": "1"});
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    CachedNetworkImage headImage = CachedNetworkImage(
        imageUrl: _consignProduct.sellerAvatar ?? "",
        imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(8.r),
                      topLeft: Radius.circular(8.r)),
                  image:
                      DecorationImage(image: imageProvider, fit: BoxFit.cover)),
            ),
        errorWidget: (context, url, error) =>
            Image.asset("assets/images/app_icon.png"));

    bool onFlag = _consignProduct.orderStatus == "-1";

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 30,
              width: 30,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(50.0), child: headImage),
            ),
            const Padding(padding: EdgeInsets.only(right: 5)),
            Text(
              _consignProduct.sellerName ?? "",
              style: const TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Card(
            color: Colors.white,
            elevation: 0,
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(0)),
            ),
            child: Padding(
              padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Expanded(
                    flex: 1,
                    child: SizedBox(
                      height: 70.w,
                      width: 70.w,
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(8.r),
                          child: CachedNetworkImage(
                              imageUrl: _consignDetailVo.mainImageUrl ?? "",
                              imageBuilder: (context, imageProvider) =>
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(8.r)),
                                        image: DecorationImage(
                                            image: imageProvider,
                                            fit: BoxFit.cover)),
                                  ),
                              errorWidget: (context, url, error) =>
                                  Image.asset("assets/images/app_icon.png"))),
                    ),
                  ),
                  Expanded(
                    flex: 4,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: 22.w,
                            child: Padding(
                              padding: EdgeInsets.only(left: 4.w),
                              child: Text(_consignDetailVo.title ?? '***',
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 14.sp,
                                      color: const Color(0xFF262626)),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis),
                            ),
                          ),
                          SizedBox(
                            height: 40.w,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Padding(
                                  padding:
                                      EdgeInsets.only(left: 4.w, top: 18.w),
                                  child: Text(
                                      '￥${_consignDetailVo.price ?? 0.00}',
                                      style: TextStyle(
                                          fontFamily: "PingFang SC",
                                          fontWeight: FontWeight.w700,
                                          fontSize: 16.sp,
                                          color: const Color(0xFFF55F4E)),
                                      textAlign: TextAlign.left),
                                ),
                                SizedBox(
                                  height: 35.w,
                                  child: TextButton(
                                      onPressed: () async {
                                        if (!(_consignDetailVo.seller ??
                                                false) &&
                                            onFlag) {
                                          bool? confirmFlag =
                                              await _showConfirmDialog(
                                                  "确定要下单吗");
                                          if (confirmFlag != null &&
                                              confirmFlag) {
                                            _orderCreate();
                                          }
                                        } else {
                                          EcyRouter.push(context,
                                              EcyRouter.consignmentDetailPage, {
                                            "productId":
                                                _consignProduct.productId
                                          });
                                        }
                                      },
                                      style: const ButtonStyle(
                                        backgroundColor: WidgetStatePropertyAll(
                                            Color(0xFFFF3E9F)),
                                      ),
                                      child: Text(
                                        (_consignDetailVo.seller ?? false)
                                            ? "查看详情"
                                            : onFlag
                                                ? "立即下单"
                                                : "查看详情",
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w700,
                                            fontSize: 14.sp,
                                            color: const Color(0xFFFFFFFF)),
                                      )),
                                ),
                              ],
                            ),
                          ),
                        ]),
                  ),
                ],
              ),
            ),
          ),
          if (_consignDetailVo.orderStatus == "0" &&
                  (_consignDetailVo.seller ?? false) ||
              (_consignDetailVo.orderStatus == "1" &&
                  (_consignDetailVo.buyer ?? false)))
            Container(
              height: 32.w,
              color: const Color.fromARGB(25, 255, 83, 169),
              padding: const EdgeInsets.only(
                left: 8,
              ),
              child: Align(
                  alignment: Alignment.centerLeft,
                  child: RichText(
                      text: TextSpan(
                    children: [
                      const WidgetSpan(
                          child: Icon(
                        CupertinoIcons.exclamationmark_circle,
                        color: Color(0xFFEA4B9B),
                        size: 17,
                      )),
                      TextSpan(
                          text: _consignDetailVo.orderStatus == "0"
                              ? " 对方已确认下单，请尽快将宝贝送至寄售点"
                              : " 卖家已将宝贝送至寄售点，请尽快提货",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14.sp,
                            color: const Color(0xFFEA4B9B),
                          ))
                    ],
                  ))),
            ),
          const Padding(padding: EdgeInsets.only(bottom: 5)),
          Expanded(child: _sessionId != null ? _chatScreen : Container()),
        ],
      ),
    );
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 120.w,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 70.w,
                  child: Padding(
                    padding: EdgeInsets.only(top: 20.w, bottom: 20.w),
                    child: Text(
                      content,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w400,
                          fontSize: 17.sp,
                          color: const Color(0xFF262626)),
                    ),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: Text(
                              '取消',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w400,
                                  fontSize: 16.sp,
                                  color: const Color(0xFF262626)),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: Text(
                            '确认',
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: const Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
